<template>
  <div style="width: 256px">
    <a-menu :selected-keys="selectedKeys" :open-keys.sync="openKeys" mode="inline" :theme="theme">
      <template v-for="item in menuData">
        <a-menu-item
          v-if="!item.children"
          :key="item.path"
          @click="() => $router.push({ path: item.path, query: $route.query })"
        >
          <a-icon v-if="item.meta.icon" :type="item.meta.icon" />
          <span>{{ item.meta.title }}</span>
        </a-menu-item>
        <sub-menu v-else :key="item.path" :menu-info="item" />
      </template>
    </a-menu>
  </div>
</template>

<script>
import SubMenu from "./SubMenu";
import { check } from "../utils/auth";

export default {
  components: {
    "sub-menu": SubMenu,
  },
  props: {
    theme: {
      type: String,
      default: "dark",
    },
  },
  watch: {
    "$route.path": function(val) {
      this.selectedKeys = this.selectKeysMap[val];
      this.openKeys = this.collapsed ? [] : this.openKeysMap[val];
    },
  },
  data() {
    this.openKeysMap = {};
    this.selectKeysMap = {};
    const menuData = this.getMenuData(this.$router.options.routes);
    console.log(this.openKeysMap);
    console.log(this.selectKeysMap);
    return {
      collapsed: false,
      menuData: menuData,
      selectedKeys: this.selectKeysMap[this.$route.path],
      openKeys: this.collapsed ? [] : this.openKeysMap[this.$route.path],
    };
  },
  methods: {
    toggleCollapsed() {
      this.collapsed = !this.collapsed;
    },
    menuItemClick(item) {
      console.log(JSON.stringify(item));
      // this.$router.push({ path: item.path });
    },
    getMenuData(routes = [], parentKeys = [], selectKey) {
      const menuData = [];
      for (let item of routes) {
        if (item.meta && item.meta.authority && !check(item.meta.authority)) {
          break;
        }
        if (item.name && !item.hideInMenu) {
          this.openKeysMap[item.path] = parentKeys;
          this.selectKeysMap[item.path] = [selectKey || item.path];
          const newItem = { ...item };
          delete newItem.children;
          if (item.children && !item.hideChildrenInMenu) {
            newItem.children = this.getMenuData(item.children, [...parentKeys, item.path]);
          } else {
            this.getMenuData(
              item.children,
              selectKey ? parentKeys : [...parentKeys, item.path],
              selectKey || item.path,
            );
          }
          menuData.push(newItem);
        } else if (!item.hideInMenu && !item.hideChildrenInMenu && item.children) {
          menuData.push(...this.getMenuData(item.children, [...parentKeys, item.path]));
        }
      }

      return menuData;
    },
  },
};
</script>
